package com.xing.activity;

import com.xing.controller.CommonController;
import com.xing.controller.DBController;
import com.xing.model.HsdAccount;
import com.xing.my_model.HsdAccountObject;
import com.xing.questionnairesurvey.R;
import com.xing.util.Common;
import com.xing.util.CurrentUserUtil;
import com.xing.util.DeviceUtil;
import com.xing.util.MD5;
import com.xing.util.SharedPreferenceUtil;
import com.xing.util.ViewUtil;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class LoginActivity extends Activity {

	private EditText userNameEditText;
	private EditText pwdEditText;
	private ImageView isRememberPwd;
	private ImageView isRememberUserName;
	private Button loginButton,cancelButton;
	private boolean isRememberPwdFlag;
	private boolean isRememberUserNameFlag;
	private String loginid;
	private String pwd;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		isRememberPwdFlag = false;
		isRememberUserNameFlag = false;
		
		initWidgets();
		getUserInfo();
		
	}

	private void initWidgets(){
		userNameEditText = (EditText) findViewById(R.id.user_name);
		pwdEditText = (EditText) findViewById(R.id.pwd);
		isRememberPwd = (ImageView) findViewById(R.id.is_remember_pwd);
		isRememberUserName = (ImageView) findViewById(R.id.is_remember_username);
		loginButton = (Button) findViewById(R.id.login_btn);
		cancelButton = (Button) findViewById(R.id.cancel_btn);
		
		loginButton.setOnClickListener(myListener);
		isRememberPwd.setOnClickListener(myListener);
		isRememberUserName.setOnClickListener(myListener);
		cancelButton.setOnClickListener(myListener);
	}
	
	private void saveUserInfo(){
		if (isRememberUserNameFlag) {
			SharedPreferenceUtil.putStringInfo(LoginActivity.this, SharedPreferenceUtil.userName, loginid);
		}else {
			SharedPreferenceUtil.clearStringInfo(LoginActivity.this, SharedPreferenceUtil.userName);
		}
		
		if (isRememberPwdFlag) {
			SharedPreferenceUtil.putStringInfo(LoginActivity.this, SharedPreferenceUtil.userPwd, pwd);
		}else {
			SharedPreferenceUtil.clearStringInfo(LoginActivity.this, SharedPreferenceUtil.userPwd);
		}
		
		SharedPreferenceUtil.putBooleanInfo(LoginActivity.this, SharedPreferenceUtil.isRememberUserName, isRememberUserNameFlag);
		SharedPreferenceUtil.putBooleanInfo(LoginActivity.this, SharedPreferenceUtil.isRememberPwd, isRememberPwdFlag);
	}
	
	private void getUserInfo(){
		String userName = SharedPreferenceUtil.getStringInfo(LoginActivity.this, SharedPreferenceUtil.userName);
		String pwd = SharedPreferenceUtil.getStringInfo(LoginActivity.this, SharedPreferenceUtil.userPwd);
		if (!TextUtils.isEmpty(userName)) {
			userNameEditText.setText(userName);
		}
		
		if (!TextUtils.isEmpty(pwd)) {
			pwdEditText.setText(pwd);
		}
		
		isRememberUserNameFlag = SharedPreferenceUtil.getBooleanInfo(LoginActivity.this, SharedPreferenceUtil.isRememberUserName);
		isRememberPwdFlag = SharedPreferenceUtil.getBooleanInfo(LoginActivity.this, SharedPreferenceUtil.isRememberPwd);
		

		if (isRememberUserNameFlag) {
			isRememberUserName.setBackgroundResource(R.drawable.checkbox_on);
		}
		
		if (isRememberPwdFlag) {
			isRememberPwd.setBackgroundResource(R.drawable.checkbox_on);
		}
		
	}
	
	
	public OnClickListener myListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.login_btn:
				loginid = userNameEditText.getText().toString().trim();
			    pwd = pwdEditText.getText().toString().trim();
			    
			    DBController.getInstance().getHsdAccount(LoginActivity.this, loginid, getHsdAccountHandler);
				break;

			case R.id.is_remember_pwd:
				if (!isRememberPwdFlag) {
					isRememberPwd.setBackgroundResource(R.drawable.checkbox_on);
					isRememberPwdFlag = true;
				}else{
					isRememberPwd.setBackgroundResource(R.drawable.checkbox_off);
					isRememberPwdFlag = false;
				}
			break;
			case R.id.is_remember_username:
				if (!isRememberUserNameFlag) {
					isRememberUserName.setBackgroundResource(R.drawable.checkbox_on);
					isRememberUserNameFlag = true;
				}else{
					isRememberUserName.setBackgroundResource(R.drawable.checkbox_off);
					isRememberUserNameFlag = false;
				}
				break;
			case R.id.cancel_btn:
				quitApp();
				break;
			default:
				break;
			}
			
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quitApp();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void quitApp(){
		new AlertDialog.Builder(LoginActivity.this).setTitle("提示").setMessage("您确定退出应用程序吗?").setPositiveButton("确定", 
			    new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						LoginActivity.this.finish();
					}
				}).setNegativeButton("取消",new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				}).show();
	}
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			HsdAccountObject hsdAccountObject = (HsdAccountObject) msg.obj;
			if (hsdAccountObject.status == 1) {
				    saveUserInfo();
				    CurrentUserUtil.loginid = hsdAccountObject.getUserinfo().getLoginid();
				    CurrentUserUtil.userName = hsdAccountObject.getUserinfo().getUsername();
				    CurrentUserUtil.token = hsdAccountObject.getUserinfo().getApptoken();
				    
				    DBController.getInstance().insertHsdAccount(LoginActivity.this, hsdAccountObject.getUserinfo().getUsername(), hsdAccountObject.getUserinfo().getPassword(), hsdAccountObject.getUserinfo().getLoginid(),hsdAccountObject.getUserinfo().getApptoken(),saveAccountHandler);
				 	Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
					startActivity(intent);
			}else{
				ViewUtil.showToast(LoginActivity.this,hsdAccountObject.msg);
			}
		}
	};

	private Handler saveAccountHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			boolean isInsert =  (Boolean) msg.obj;
			if (isInsert) {
				   
			}else{
				ViewUtil.showToast(LoginActivity.this,"本地账号信息保存失败");
			}
		}
	};
	
	private Handler getHsdAccountHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			HsdAccount hsdAccount = (HsdAccount) msg.obj;
			if (hsdAccount != null) {
				   if (!TextUtils.isEmpty(pwd) && MD5.md5(pwd).equalsIgnoreCase(hsdAccount.getPassword())) {
					   
					    CurrentUserUtil.loginid = hsdAccount.getLoginid();
					    CurrentUserUtil.userName = hsdAccount.getUsername();
					    CurrentUserUtil.token = hsdAccount.getApptoken();
					    
					 	Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
						startActivity(intent);
				 }else {
					 ViewUtil.showToast(LoginActivity.this, "密码错误!");
				 }
			}else{
				if (Common.isNetworkAvailable(LoginActivity.this)) {
					String deviceId = DeviceUtil.getDeviceId(LoginActivity.this);
				    CommonController.getInstance().login(LoginActivity.this, loginid, pwd, deviceId, handler);
				    
				}else {
					ViewUtil.showToast(LoginActivity.this, "账号首次在此设备登录，请联网操作!");
				}
				
			}
		}
	};
	
}
